<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户优惠券管理</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="../css/common.css">
</head>
<body>
<div class="container">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>用户优惠券管理</h2>
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#userCouponModal">
            新增用户优惠券
        </button>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
        <div class="row g-3">
            <div class="col-md-3">
                <select id="searchUserId" class="form-select">
                    <option value="">全部用户</option>
                </select>
            </div>
            <div class="col-md-3">
                <select id="searchTemplateId" class="form-select">
                    <option value="">全部模板</option>
                </select>
            </div>
            <div class="col-md-3">
                <select id="searchCouponStatus" class="form-select">
                    <option value="">全部状态</option>
                    <option value="0">未使用</option>
                    <option value="1">锁定</option>
                    <option value="2">已使用</option>
                    <option value="3">已过期</option>
                    <option value="4">已撤回</option>
                </select>
            </div>
            <div class="col-md-3">
                <button class="btn btn-success w-100" onclick="queryUserCouponList(1)">搜索</button>
            </div>
        </div>
    </div>

    <!-- 用户优惠券列表 -->
    <div class="card">
        <div class="card-body">
            <table class="table table-hover table-bordered">
                <thead class="table-primary">
                <tr>
                    <th>记录ID</th>
                    <th>用户</th>
                    <th>优惠券模板</th>
                    <th>领取时间</th>
                    <th>领取数量</th>
                    <th>状态</th>
                    <th>有效期</th>
                    <th>使用时间</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody id="userCouponTableBody">
                <tr><td colspan="9" class="text-center">加载中...</td></tr>
                </tbody>
            </table>
        </div>
    </div>

    <!-- 分页 -->
    <div id="pagination-container"></div>
</div>

<!-- 新增/编辑用户优惠券弹窗 -->
<div class="modal fade" id="userCouponModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTitle">新增用户优惠券</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="userCouponForm">
                    <input type="hidden" id="couponId">
                    <div class="mb-3">
                        <label for="userId" class="form-label">用户 <span class="text-danger">*</span></label>
                        <select class="form-select" id="userId" required>
                            <option value="">请选择用户</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="couponTemplateId" class="form-label">优惠券模板 <span class="text-danger">*</span></label>
                        <select class="form-select" id="couponTemplateId" required onchange="loadTemplateValidity()">
                            <option value="">请选择模板</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="receiveNum" class="form-label">领取数量 <span class="text-danger">*</span></label>
                        <input type="number" min="1" max="10" class="form-control" id="receiveNum" required placeholder="单次领取数量（1-10）">
                    </div>
                    <div class="mb-3">
                        <label for="couponStatus" class="form-label">状态 <span class="text-danger">*</span></label>
                        <select class="form-select" id="couponStatus" required>
                            <option value="0">未使用</option>
                            <option value="1">锁定</option>
                            <option value="2">已使用</option>
                            <option value="3">已过期</option>
                            <option value="4">已撤回</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="validStartTime" class="form-label">生效时间 <span class="text-danger">*</span></label>
                        <input type="datetime-local" class="form-control" id="validStartTime" required>
                    </div>
                    <div class="mb-3">
                        <label for="validEndTime" class="form-label">失效时间 <span class="text-danger">*</span></label>
                        <input type="datetime-local" class="form-control" id="validEndTime" required>
                    </div>
                    <div class="mb-3" id="useTimeGroup" style="display: none;">
                        <label for="useTime" class="form-label">使用时间</label>
                        <input type="datetime-local" class="form-control" id="useTime">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="saveUserCoupon()">保存</button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="../js/common.js"></script>
<script>
    let currentPage = 1;
    const pageSize = 10;
    let templateList = []; // 存储优惠券模板列表

    window.onload = function () {
        // 加载用户和模板列表
        SelectData.loadUsers("searchUserId");
        SelectData.loadUsers("userId");
        loadCouponTemplates();

        // 监听状态变化，显示/隐藏使用时间
        document.getElementById("couponStatus").addEventListener("change", function () {
            document.getElementById("useTimeGroup").style.display = this.value === "2" ? "block" : "none";
        });

        queryUserCouponList(currentPage);
    };

    // 加载优惠券模板（含有效期）
    async function loadCouponTemplates() {
        try {
            const res = await axios.get("/api/coupon-templates/all");
            templateList = res.data;
            const templateSelect = document.getElementById("couponTemplateId");
            const searchTemplateSelect = document.getElementById("searchTemplateId");

            templateList.forEach(tpl => {
                const optionText = `${tpl.id} - ${tpl.name}（${tpl.type === 0 ? '立减券' : tpl.type === 1 ? '满减券' : '折扣券'}）`;
                templateSelect.innerHTML += `<option value="${tpl.id}" data-start="${tpl.validStartTime}" data-end="${tpl.validEndTime}">${optionText}</option>`;
                searchTemplateSelect.innerHTML += `<option value="${tpl.id}">${optionText}</option>`;
            });
        } catch (err) {
            Common.errorMsg("加载优惠券模板失败：" + err.message);
        }
    }

    // 选择模板后自动填充有效期
    function loadTemplateValidity() {
        const templateId = document.getElementById("couponTemplateId").value;
        const template = templateList.find(tpl => tpl.id == templateId);
        if (template) {
            document.getElementById("validStartTime").value = moment(template.validStartTime).format("YYYY-MM-DDTHH:mm");
            document.getElementById("validEndTime").value = moment(template.validEndTime).format("YYYY-MM-DDTHH:mm");
        }
    }

    // 查询用户优惠券列表
    async function queryUserCouponList(pageNum) {
        try {
            const userId = document.getElementById("searchUserId").value;
            const templateId = document.getElementById("searchTemplateId").value;
            const status = document.getElementById("searchCouponStatus").value;

            const res = await axios.get("/api/user-coupons/page", {
                params: {
                    pageNum,
                    pageSize,
                    userId: userId || undefined,
                    couponTemplateId: templateId || undefined,
                    status: status || undefined
                }
            });

            const { records, total } = res.data;
            currentPage = pageNum;
            const tableBody = document.getElementById("userCouponTableBody");
            tableBody.innerHTML = "";

            if (records.length === 0) {
                tableBody.innerHTML = '<tr><td colspan="9" class="text-center">暂无数据</td></tr>';
                return;
            }

            records.forEach(coupon => {
                const validPeriod = `${Common.formatDate(coupon.validStartTime).split(" ")[0]} 至 ${Common.formatDate(coupon.validEndTime).split(" ")[0]}`;
                const row = `
                        <tr>
                            <td>${coupon.id}</td>
                            <td>${coupon.user?.username || "未知用户"}（${coupon.user?.phone || ""}）</td>
                            <td>${coupon.couponTemplate?.name || "未知模板"}</td>
                            <td>${Common.formatDate(coupon.receiveTime)}</td>
                            <td>${coupon.receiveNum}</td>
                            <td>${Common.formatCouponStatus(coupon.status)}</td>
                            <td>${validPeriod}</td>
                            <td>${coupon.useTime ? Common.formatDate(coupon.useTime) : "无"}</td>
                            <td>
                                <button class="btn btn-sm btn-outline-primary" onclick="editUserCoupon(${coupon.id})">编辑</button>
                                <button class="btn btn-sm btn-outline-danger" onclick="deleteUserCoupon(${coupon.id})">删除</button>
                            </td>
                        </tr>
                    `;
                tableBody.innerHTML += row;
            });

            Common.renderPagination(total, pageNum, pageSize, queryUserCouponList);
        } catch (err) {
            Common.errorMsg("查询用户优惠券失败：" + err.message);
            document.getElementById("userCouponTableBody").innerHTML = '<tr><td colspan="9" class="text-center">查询失败</td></tr>';
        }
    }

    // 编辑用户优惠券
    async function editUserCoupon(couponId) {
        try {
            const res = await axios.get(`/api/user-coupons/${couponId}`);
            const coupon = res.data;

            document.getElementById("couponId").value = coupon.id;
            document.getElementById("userId").value = coupon.userId;
            document.getElementById("couponTemplateId").value = coupon.couponTemplateId;
            document.getElementById("receiveNum").value = coupon.receiveNum;
            document.getElementById("couponStatus").value = coupon.status;
            document.getElementById("validStartTime").value = moment(coupon.validStartTime).format("YYYY-MM-DDTHH:mm");
            document.getElementById("validEndTime").value = moment(coupon.validEndTime).format("YYYY-MM-DDTHH:mm");
            document.getElementById("useTime").value = coupon.useTime ? moment(coupon.useTime).format("YYYY-MM-DDTHH:mm") : "";
            document.getElementById("modalTitle").textContent = "编辑用户优惠券";

            // 显示/隐藏使用时间
            document.getElementById("useTimeGroup").style.display = coupon.status === 2 ? "block" : "none";

            new bootstrap.Modal(document.getElementById("userCouponModal")).show();
        } catch (err) {
            Common.errorMsg("加载用户优惠券信息失败：" + err.message);
        }
    }

    // 保存用户优惠券
    async function saveUserCoupon() {
        const userId = document.getElementById("userId").value;
        const couponTemplateId = document.getElementById("couponTemplateId").value;
        const receiveNum = document.getElementById("receiveNum").value;
        const status = document.getElementById("couponStatus").value;
        const validStartTime = document.getElementById("validStartTime").value;
        const validEndTime = document.getElementById("validEndTime").value;
        const useTime = document.getElementById("useTime").value;
        const couponId = document.getElementById("couponId").value;

        // 校验必填字段
        if (!userId || !couponTemplateId || !receiveNum || !validStartTime || !validEndTime) {
            Common.errorMsg("请填写必填字段！");
            return;
        }

        // 构建数据
        const couponData = {
            userId: parseInt(userId),
            couponTemplateId: parseInt(couponTemplateId),
            receiveNum: parseInt(receiveNum),
            status: parseInt(status),
            validStartTime: new Date(validStartTime).getTime(),
            validEndTime: new Date(validEndTime).getTime(),
            useTime: useTime ? new Date(useTime).getTime() : null,
            receiveTime: couponId ? undefined : new Date().getTime() // 新增时自动生成领取时间
        };

        try {
            if (couponId) {
                couponData.id = parseInt(couponId);
                await axios.put("/api/user-coupons", couponData);
                Common.successMsg("编辑用户优惠券成功！");
            } else {
                await axios.post("/api/user-coupons", couponData);
                Common.successMsg("新增用户优惠券成功！");
            }

            bootstrap.Modal.getInstance(document.getElementById("userCouponModal")).hide();
            queryUserCouponList(currentPage);
            document.getElementById("userCouponForm").reset();
            document.getElementById("couponId").value = "";
            document.getElementById("modalTitle").textContent = "新增用户优惠券";
            document.getElementById("useTimeGroup").style.display = "none";
        } catch (err) {
            Common.errorMsg("保存用户优惠券失败：" + err.message);
        }
    }

    // 删除用户优惠券（逻辑删除）
    function deleteUserCoupon(couponId) {
        Common.confirmMsg("确定要删除该用户优惠券吗？（逻辑删除）", async () => {
            try {
                await axios.delete(`/api/user-coupons/${couponId}`);
                Common.successMsg("删除用户优惠券成功！");
                queryUserCouponList(currentPage);
            } catch (err) {
                Common.errorMsg("删除用户优惠券失败：" + err.message);
            }
        });
    }
</script>
</body>
</html>